<template>
    <div class="role-management">
        <el-card>
            <template #header>
                <div class="card-header">
                    <span>角色管理</span>
                    <el-button type="primary" @click="showAddDialog = true">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        添加角色
                    </el-button>
                </div>
            </template>

            <!-- 搜索区域 -->
            <div class="search-area">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-input v-model="searchForm.search" placeholder="搜索角色名称" @keyup.enter="handleSearch"
                            clearable>
                            <template #append>
                                <el-button @click="handleSearch">
                                    <el-icon>
                                        <Search />
                                    </el-icon>
                                </el-button>
                            </template>
                        </el-input>
                    </el-col>
                    <el-col :span="4">
                        <el-button @click="resetSearch">重置</el-button>
                    </el-col>
                </el-row>
            </div>

            <!-- 角色表格 -->
            <CommonTable :loading="loading" :data="roles" :offset="280" table-style="width: 100%">
                <el-table-column prop="id" label="ID" width="80" sortable />
                <el-table-column prop="name" label="角色名称" sortable />
                <el-table-column prop="description" label="描述" sortable />
                <el-table-column prop="user_count" label="用户数量" width="100" sortable />
                <el-table-column prop="menu_count" label="菜单权限" width="100" sortable />
                <el-table-column prop="created_at" label="创建时间" sortable />
                <el-table-column label="操作" width="220" fixed="right">
                    <template #default="{ row }">
                        <el-button size="small" @click="editRole(row)">编辑</el-button>
                        <el-button size="small" type="info" @click="viewPermissions(row)">权限</el-button>
                        <el-button size="small" type="danger" @click="deleteRole(row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </CommonTable>

            <!-- 分页 -->
            <div class="pagination">
                <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.per_page"
                    :page-sizes="[10, 20, 50, 100]" :total="pagination.total"
                    layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <!-- 添加/编辑角色对话框 -->
        <el-dialog v-model="showAddDialog" :title="editingRole ? '编辑角色' : '添加角色'" width="600px" @closed="resetForm">
            <el-form ref="roleFormRef" :model="roleForm" :rules="roleRules" label-width="80px">
                <el-form-item label="角色名称" prop="name">
                    <el-input v-model="roleForm.name" />
                </el-form-item>

                <el-form-item label="描述" prop="description">
                    <el-input v-model="roleForm.description" type="textarea" rows="3" />
                </el-form-item>

                <el-form-item label="菜单权限" prop="menu_ids">
                    <el-tree ref="menuTreeRef" :data="menuTree" :props="{ children: 'children', label: 'name' }"
                        node-key="id" show-checkbox check-strictly class="menu-tree" />
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showAddDialog = false">取消</el-button>
                    <el-button type="primary" :loading="submitLoading" @click="submitRole">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 权限查看对话框 -->
        <el-dialog v-model="showPermissionDialog" title="角色权限" width="500px">
            <div v-if="selectedRole">
                <h4>{{ selectedRole.name }} 的权限</h4>
                <el-tree :data="permissionTree" :props="{ children: 'children', label: 'name' }" default-expand-all />
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import CommonTable from '@/components/CommonTable.vue'

const loading = ref(false)
const submitLoading = ref(false)
const showAddDialog = ref(false)
const showPermissionDialog = ref(false)
const editingRole = ref(null)
const selectedRole = ref(null)

const roles = ref([])
const menuTree = ref([])
const permissionTree = ref([])

const menuTreeRef = ref()
const roleFormRef = ref()

const searchForm = reactive({
    search: ''
})

const pagination = reactive({
    page: 1,
    per_page: 10,
    total: 0,
    pages: 0
})

const roleForm = reactive({
    name: '',
    description: '',
    menu_ids: []
})

const roleRules = {
    name: [
        { required: true, message: '请输入角色名称', trigger: 'blur' },
        { min: 2, max: 20, message: '角色名称长度在 2 到 20 个字符', trigger: 'blur' }
    ]
}

// 获取角色列表
const fetchRoles = async () => {
    loading.value = true
    try {
        const params = {
            page: pagination.page,
            per_page: pagination.per_page,
            search: searchForm.search
        }

        const response = await axios.get('/api/roles', { params })
        roles.value = response.data.roles
        pagination.total = response.data.total
        pagination.pages = response.data.pages
    } catch (error) {
        ElMessage.error('获取角色列表失败: ' + (error.response?.data?.message || error.message))
    } finally {
        loading.value = false
    }
}

// 获取菜单树
const fetchMenuTree = async () => {
    try {
        const response = await axios.get('/api/menus')
        menuTree.value = response.data.menus
    } catch (error) {
        ElMessage.error('获取菜单列表失败: ' + (error.response?.data?.message || error.message))
    }
}

// 搜索
const handleSearch = () => {
    pagination.page = 1
    fetchRoles()
}

// 重置搜索
const resetSearch = () => {
    searchForm.search = ''
    pagination.page = 1
    fetchRoles()
}

// 分页
const handleSizeChange = (val) => {
    pagination.per_page = val
    pagination.page = 1
    fetchRoles()
}

const handleCurrentChange = (val) => {
    pagination.page = val
    fetchRoles()
}

// 编辑角色
const editRole = async (role) => {
    editingRole.value = role
    roleForm.name = role.name
    roleForm.description = role.description

    try {
        // 获取角色详情和权限
        const response = await axios.get(`/api/roles/${role.id}`)
        const roleData = response.data.role

        showAddDialog.value = true

        // 等待对话框渲染完成后设置选中的菜单
        await nextTick()
        if (menuTreeRef.value) {
            const menuIds = roleData.menus.map(menu => menu.id)
            menuTreeRef.value.setCheckedKeys(menuIds)
        }
    } catch (error) {
        ElMessage.error('获取角色详情失败: ' + (error.response?.data?.message || error.message))
    }
}

// 查看权限
const viewPermissions = async (role) => {
    try {
        const response = await axios.get(`/api/roles/${role.id}`)
        selectedRole.value = response.data.role
        permissionTree.value = response.data.role.menus
        showPermissionDialog.value = true
    } catch (error) {
        ElMessage.error('获取角色权限失败: ' + (error.response?.data?.message || error.message))
    }
}

// 删除角色
const deleteRole = async (role) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除角色 "${role.name}" 吗？`,
            '删除确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        await axios.delete(`/api/roles/${role.id}`)
        ElMessage.success('删除成功')
        fetchRoles()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message))
        }
    }
}

// 提交角色表单
const submitRole = async () => {
    if (!roleFormRef.value) return

    await roleFormRef.value.validate(async (valid) => {
        if (valid) {
            submitLoading.value = true
            try {
                const data = { ...roleForm }

                // 获取选中的菜单ID
                if (menuTreeRef.value) {
                    data.menu_ids = menuTreeRef.value.getCheckedKeys()
                }

                if (editingRole.value) {
                    await axios.put(`/api/roles/${editingRole.value.id}`, data)
                    ElMessage.success('更新成功')
                } else {
                    await axios.post('/api/roles', data)
                    ElMessage.success('创建成功')
                }

                showAddDialog.value = false
                fetchRoles()
            } catch (error) {
                ElMessage.error((editingRole.value ? '更新' : '创建') + '失败: ' + (error.response?.data?.message || error.message))
            } finally {
                submitLoading.value = false
            }
        }
    })
}

// 重置表单
const resetForm = () => {
    editingRole.value = null
    roleForm.name = ''
    roleForm.description = ''
    roleForm.menu_ids = []
    roleFormRef.value?.resetFields()
    if (menuTreeRef.value) {
        menuTreeRef.value.setCheckedKeys([])
    }
}

onMounted(() => {
    fetchRoles()
    fetchMenuTree()
})
</script>

<style scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.search-area {
    margin-bottom: 20px;
}

.pagination {
    margin-top: 20px;
    text-align: right;
}

.menu-tree {
    max-height: 300px;
    overflow-y: auto;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 10px;
}
</style>